package com.qingke.qkmall.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qingke.qkmall.dao.ShopMapper;
import com.qingke.qkmall.pojo.Shop;
import com.qingke.qkmall.pojo.ShopQueryVo;
import com.qingke.qkmall.serviceInterface.ShopService;

/**
 * 商品Service
 * @author Administrator
 *
 */
@Service
public class ShopServiceImpl implements ShopService {
	@Autowired
	private ShopMapper shopMapper;

	/**
	 * 添加商品
	 * 
	 * @param bsqv
	 * @return
	 */
	public int insertShop(ShopQueryVo sqv) {
		//System.out.println(sqv.getCategory() + "," + sqv.getShop().getShopName());
		//有这个名字的数据则不插入
//		if(selectShopByName(sqv.getShop().getShopName().trim()) != null) {
//			return -1;
//		}
		int result = 0;
		shopMapper.insertShop(sqv);
		// 1书本 2衣服 3食物
		if (sqv.getCategory() == 1) {
			result = shopMapper.insertBook(sqv);
		} else if (sqv.getCategory() == 2) {
			result = shopMapper.insertClothes(sqv);
		} else {
			if(sqv.getFood().getFoodProdeceDate() == null) {
				System.out.println(sqv.getFood().getFoodProdeceDate());
				result = 0;
			} else {
				result = shopMapper.insertFood(sqv);
			} 
		}
		if(result == 0) {
			//如果添加失败就删除
			deleteShop(sqv.getShop().getShopId());
			return result;
		}
		return result;
	}

	/**
	 * 查询所有商品
	 * 
	 * @return
	 */
	public List<ShopQueryVo> selectAllShop(Integer id) {
		List<ShopQueryVo> result = new ArrayList<>();
		List<Shop> shopList = shopMapper.selectAllShop(id);
		for (Shop shop : shopList) {
			ShopQueryVo sqv = new ShopQueryVo();
			int shopId = shop.getShopId();
			int categoryId = shop.getShopCategoryId();
			sqv.setShop(shop);
			if (categoryId == 1) {
				sqv.setBook(shopMapper.selectBookByShopId(shopId));
			} else if (categoryId == 2) {
				sqv.setClothes(shopMapper.selectClothesByShopId(shopId));
			} else if (categoryId == 3) {
				sqv.setFood(shopMapper.selectFoodByShopId(shopId));
			}

			result.add(sqv);
		}

		return result;
	}

	/**
	 * 通过名字查询商品
	 */
	public Shop selectShopByName(String shopName) {
		return shopMapper.selectShopByName(shopName);
	}

	@Override
	public int deleteShop(int id) {
		return shopMapper.deleteShop(id);
	}

	@Override
	public ShopQueryVo selectShopById(int shopId) {
		ShopQueryVo sqv = new ShopQueryVo();
		Shop shop = shopMapper.selectShopById(shopId);
		int categoryId = shop.getShopCategoryId();
		sqv.setShop(shop);
		if (categoryId == 1) {
			sqv.setBook(shopMapper.selectBookByShopId(shopId));
		} else if (categoryId == 2) {
			sqv.setClothes(shopMapper.selectClothesByShopId(shopId));
		} else if (categoryId == 3){
			sqv.setFood(shopMapper.selectFoodByShopId(shopId));
		}
		return sqv;
	}
}
